package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-05
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private WechatServiceImpl wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 用户登录
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1、远程调用appid+appsecret+code ----> openid
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        //2、openid去数据库查询当前用户是否登陆过zzyl小程序
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openId);
        FamilyMember familyMember = getOne(queryWrapper);

        //2.1 远程调用appid+appsecret+phoneCode 去微信官方查询手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        if (familyMember == null) {
            familyMember = new FamilyMember();
            //3、没有值，新增一个数据
            familyMember.setOpenId(openId);
            familyMember.setPhone(phone);
            familyMember.setGender(1);
            familyMember.setName("单中秋");
            save(familyMember);
        } else if (ObjectUtil.isNotEmpty(familyMember.getPhone()) && !familyMember.getPhone().equals(phone)) {
            //4、有值，更新数据，微信官方查询手机号和数据表中的手机号是否相等
            UpdateWrapper<FamilyMember> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("phone", phone).eq("open_id", openId);
            update(updateWrapper);
        }
        // 5、将用户id存入token,返回
        Map<String, Object> map = new HashMap<>();
        map.put("userId", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map);

        //将需要的数据封装成LoginVo返回给前端
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }
}
